<template>
  <div class="chat-container">
    <div class="chat-messages" ref="chatMessages">
      <div v-for="(msg, index) in filteredMessages" :key="index" :class="['message', msg.role]">
        <div class="message-content markdown-body" v-html="renderMarkdown(msg.content)"></div>
      </div>
      <div v-if="isStreaming" class="message assistant">
        <div class="message-content markdown-body" v-html="renderMarkdown(streamingMessage)"></div>
      </div>
    </div>
    <div class="chat-input">
      <button @click="showConfig = true">配置</button>
      <input v-model="userInput" @keyup.enter="sendMessage" placeholder="输入消息..." :disabled="isStreaming" />
      <button @click="sendMessage" :disabled="isStreaming">发送</button>
      <button @click="clearMessages">清理</button>
    </div>

    <!-- 配置对话框 -->
    <div v-if="showConfig" class="config-dialog">
      <div class="config-content">
        <h3>配置</h3>
        <div class="config-form">
          <label>模型名称:</label>
          <input v-model="config.model" placeholder="模型名称" />
          <label>API Key:</label>
          <input v-model="config.apiKey" placeholder="API Key" />
          <label>Base URL:</label>
          <input v-model="config.baseURL" placeholder="Base URL" />
          <label>Prompt:</label>
          <textarea v-model="config.prompt" placeholder="Prompt" rows="5"></textarea>
        </div>
        <div class="config-buttons">
          <button @click="saveConfig">保存</button>
          <button @click="showConfig = false">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import OpenAI from 'openai';
import { marked } from 'marked';
import 'github-markdown-css/github-markdown-light.css';

const messages = ref([]);
const userInput = ref('');
const streamingMessage = ref('');
const isStreaming = ref(false);
const showConfig = ref(false);

const config = ref({
  model: '',
  apiKey: '',
  baseURL: '',
  prompt: '',
});

let openai;

function initializeOpenAI() {
  if (config.value.apiKey && config.value.baseURL) {
    openai = new OpenAI({
      apiKey: config.value.apiKey,
      baseURL: config.value.baseURL,
      dangerouslyAllowBrowser: true,
    });
  }
}

function loadConfig() {
  const savedConfig = localStorage.getItem('chatConfig');
  if (savedConfig) {
    config.value = JSON.parse(savedConfig);
    initializeOpenAI();
  }
}

function saveConfig() {
  localStorage.setItem('chatConfig', JSON.stringify(config.value));
  initializeOpenAI();
  showConfig.value = false;
}

const filteredMessages = computed(() => {
  return messages.value.filter(msg => msg.role !== 'system');
});

async function sendMessage() {
  if (!userInput.value.trim()) return;

  // 添加用户消息到聊天记录
  messages.value.push({ role: 'user', content: userInput.value });
  userInput.value = '';

  // 添加系统消息（Prompt）
  if (config.value.prompt) {
    messages.value.unshift({ role: 'system', content: config.value.prompt });
  }

  // 开始流式响应
  isStreaming.value = true;
  streamingMessage.value = '';

  const stream = await openai.chat.completions.create({
    model: config.value.model,
    messages: messages.value.map(msg => ({ role: msg.role, content: msg.content })),
    stream: true,
  });

  for await (const chunk of stream) {
    streamingMessage.value += chunk.choices[0]?.delta?.content || '';
    scrollToBottom();
  }

  // 流式响应结束，添加到聊天记录
  messages.value.push({ role: 'assistant', content: streamingMessage.value });
  isStreaming.value = false;
  streamingMessage.value = '';
  scrollToBottom();

  // 移除系统消息（Prompt）
  if (config.value.prompt) {
    messages.value.shift();
  }
}

function renderMarkdown(content) {
  return marked(content);
}

function scrollToBottom() {
  nextTick(() => {
    const chatMessages = this.$refs.chatMessages;
    chatMessages.scrollTop = chatMessages.scrollHeight;
  });
}

function clearMessages() {
  messages.value = messages.value.filter(msg => msg.role === 'system');
}

onMounted(() => {
  loadConfig();
  scrollToBottom();
});
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  padding: 10px;
  box-sizing: border-box;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.message {
  margin-bottom: 10px;
}

.message.user {
  text-align: right;
}

.message.assistant {
  text-align: left;
}

.message-content {
  display: inline-block;
  padding: 8px 12px;
  border-radius: 15px;
  background-color: #f1f1f1;
  max-width: 80%;
}

.message.user .message-content {
  background-color: #007bff;
  color: white;
}

.chat-input {
  display: flex;
  align-items: center;
}

.chat-input input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
}

.chat-input button {
  padding: 8px 15px;
  border: none;
  border-radius: 5px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  margin-right: 10px;
}

.chat-input button:hover {
  background-color: #0056b3;
}

.config-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.config-content {
  background-color: white;
  padding: 20px;
  border-radius: 5px;
  width: 400px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.config-form {
  display: flex;
  flex-direction: column;
}

.config-form label {
  margin-bottom: 5px;
  font-weight: bold;
}

.config-form input,
.config-form textarea {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-bottom: 10px;
}

.config-buttons {
  display: flex;
  justify-content: flex-end;
}

.config-buttons button {
  padding: 8px 15px;
  border: none;
  border-radius: 5px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  margin-left: 10px;
}

.config-buttons button:hover {
  background-color: #0056b3;
}
</style>